package com.edu.framework.websocket.service;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.edu.common.utils.DateUtils;
import com.edu.common.utils.LogUtils;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.framework.websocket.message.base.Response;
import com.edu.framework.websocket.message.terminal.SchuduleShutDownRequest;
import com.edu.framework.websocket.message.terminal.ShutDownRequest;
import com.edu.framework.websocket.message.terminal.ShutDownVO;
import com.edu.framework.websocket.message.terminal.UpdateRequest;
import com.edu.framework.websocket.message.terminal.UpdateVO;
import com.edu.framework.websocket.message.volume.VolumeRequest;
import com.edu.system.domain.TTerminal;
import com.edu.system.domain.req.UpdateApkReq;
import com.edu.system.service.ITTerminalService;
import java.time.LocalDate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;


@Slf4j
@Service
public class TerminalService {

    @Autowired
    private ITTerminalService itTerminalService;
    @Value("${image.host}")
    private String imageHost;
    /**
     * 调整机器的音量
     * @param ids
     * @param level
     * @return
     */
    public boolean adjustVolume(Long[] ids, Integer level){
        if(ids == null || ids.length==0){
            return false;
        }
        List<TTerminal> list = this.itTerminalService.selectTTerminalListByIds(ids);
        if(CollectionUtils.isEmpty(list)){
            return false;
        }
        Response<String> response = Response.ok(VolumeRequest.TYPE, VolumeRequest.RESP_KEY,String.valueOf(level));
        for (TTerminal terminal : list) {
            String code = terminal.getCode();
            log.info("code:{} adjustVolume level {}",code,level);
            try{
                WebSocketHolder.send(code,response);
            }catch (Exception e){
                log.error("code: {} send message error: {}",code,e);
            }
        }

        return true;
    }

    /**
     * 关机
     * @param ids
     * @param
     * @return
     */
    public boolean shutDown(Long[] ids){
        if(ids == null || ids.length==0){
            return false;
        }
        List<TTerminal> list = this.itTerminalService.selectTTerminalListByIds(ids);
        if(CollectionUtils.isEmpty(list)){
            return false;
        }
        Response<Void> response = Response.ok(ShutDownRequest.TYPE, ShutDownRequest.RESP_KEY,null);
        for (TTerminal terminal : list) {
            String code = terminal.getCode();
            log.info("code:{} shutDown ");
            try{
                WebSocketHolder.send(code,response);
            }catch (Exception e){
                log.error("code: {} send message error: {}",code,e);
            }
        }

        return true;
    }

    /**
     * 定时关机开机
     * @param ids
     * @return
     */
    public boolean scheduleShutDown(Long[] ids){
        if(ids == null || ids.length==0){
            return false;
        }
        List<TTerminal> list = this.itTerminalService.selectTTerminalListByIds(ids);
        if(CollectionUtils.isEmpty(list)){
            return false;
        }
        for (TTerminal terminal : list) {
            String code = terminal.getCode();
            if (StrUtil.isBlank(terminal.getFromTo())){
                continue;
            }

            String[] split = terminal.getFromTo().split("-");
            log.info("code:{} scheduleShutDown offTime:{},onTime:{}", code, split[1], split[0]);
            try{
                LocalDate currentDate = LocalDate.now();
                ShutDownVO vo = new ShutDownVO();
                vo.setEnable(true);
                vo.setOffTime(DateUtils.toMilliTime(split[1], currentDate));
                vo.setOnTime(DateUtils.toMilliTime(split[0], currentDate.plusDays(1)));
                Response<ShutDownVO> response = Response.ok(SchuduleShutDownRequest.TYPE, SchuduleShutDownRequest.RESP_KEY,vo);

                WebSocketHolder.send(code,response);
            }catch (Exception e){
                log.error("code: {} send message error: {}",code,e);
            }
        }

        return true;
    }

    public boolean updateAPK(UpdateApkReq req){

        List<TTerminal> list = this.itTerminalService.selectTTerminalListByIds(req.getIds().toArray(new Long[0]));
        if(CollectionUtils.isEmpty(list)){
            return false;
        }
        for (TTerminal terminal : list) {
            String code = terminal.getCode();

            UpdateVO vo = new UpdateVO();
            vo.setUrl(LogUtils.mergeHost(imageHost, req.getUrl()));
            vo.setVersion(req.getVersionNo());
            log.info("send updateAPK code: {}, msg:{}", code, JSONArray.toJSONString(vo));
            try{
                Response<UpdateVO> response = Response.ok(UpdateRequest.TYPE, UpdateRequest.RESP_KEY, vo);
                WebSocketHolder.send(code,response);
            }catch (Exception e){
                log.error("code: {} send updateAPK message error: {}",code,e);
            }
        }

        return true;
    }



}
